#include "include/timer.h"

unsigned short __attribute__ ((progmem)) Prescale[] = {0,1,8,64,256,1024};

void startTimer(Timer *T)
{
  writeByte(__TCNT0__,0);
  bitSet(__TIMSK__, __TOIE0);
  writeByte(__TCCR0__, 5);
  addHandler(HWND_TIMER0, T->fHandler);
}

void startTimer0(const enum ClockSelect CS)
{
  writeByte(__TCNT0__,0);
  bitSet(__TIMSK__, __TOIE0);
  switch(CS)
  {
    case CS1024:
        writeByte(__TCCR0__, CS);
        break;
    case CS256:
        writeByte(__TCCR0__, CS);
	break;
    case CS64:
	writeByte(__TCCR0__, CS);
	break;
    case CS8:
	writeByte(__TCCR0__, CS);
	break;
    case CSNoPrescaler:
	writeByte(__TCCR0__, CS);
        break;
  };
}

void startTimer1(enum ClockSelect CS)
{
  bitSet(__TIMSK__, __TOIE1);
  writeByte(__TCNT1H__, 255);
  writeByte(__TCNT1L__, 0);
  writeByte(__TCCR1A__, 0);
  switch(CS)
  {
    case CS1024:
        writeByte(__TCCR1B__, CS);
        break;
    case CS256:
	writeByte(__TCCR1B__, CS);
	break;
    case CS64:
        writeByte(__TCCR1B__, CS);
        break;
    case CS8:
        writeByte(__TCCR1B__, CS);
        break;
    case CSNoPrescaler:
	writeByte(__TCCR1B__, CS);
	break;
  };
}

void stopTimer0()
{
  writeByte(__TCCR0__, 0);
}

void stopTimer1()
{
  writeByte(__TCCR1B__, 0);
}

void onTimer0_Overflow(void (*Handler))
{
  addHandler(HWND_TIMER0, Handler);
}

void onTimer1_Overflow(void (*Handler))
{
  addHandler(HWND_TIMER1, Handler);
}

DWORD MsToTics(DWORD ms)
{
    DWORD prescaleDiv = 1<<(pgm_read_byte(Prescale + TCCR0));
    return (ms*(F_CPU/(prescaleDiv*256)))/1000;
}
